package com.vvlive.caibao.smartcity.ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog.Builder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.vvlive.caibao.smartcity.app.SmartCityApp;
import com.vvlive.caibao.smartcity.base.BaseActivity;
import com.vvlive.caibao.smartcity.base.ListHttpCallBack;
import com.vvlive.caibao.smartcity.bean.MeetingByMonth;
import com.vvlive.caibao.smartcity.bean.MeetingRoom;
import com.vvlive.caibao.smartcity.utils.MeetingsController;
import com.vvlive.caibao.smartcity.utils.TimeUtil;
import com.vvlive.caibao.smartcity.view.CommonActionBar;
import com.vvlive.caibao.smartcity.view.DateTimePickerDialog;

import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.ui.BindView;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import smartcity.vvlive.caibao.com.smartc.R;

/**
 * Created by zhj on 2015/9/7.
 * 编辑会议
 */
public class EditMeetingActivity extends BaseActivity {

    public static HashMap<String, String> states = new HashMap<>();

    // 初始化修改会议的操作返回码
    static {
        states.put("SELF_ERROR", "其他人的会议不予修改");
        states.put("UPDATE_ERROR", "会议修改失败");
        states.put("UPDATE_RESERVE", "选择的会议室已被预定，请选择其他会议室");
        states.put("OPCODE_ERROR", "操作码不对");
        states.put("LIMIT_ERROR", "超过日期限定");
        states.put("NO_IN_GROUP", "非此机构,不能预定");
        states.put("LOGIN_ERROR", "用户账号或密码错误");
        states.put("OK", "修改会议成功");
    }

    private MeetingByMonth bean;
    @BindView(id = R.id.edit_meeting_name)
    private EditText mMeetingName;
    @BindView(id = R.id.edit_meeting_start_time, click = true)
    private TextView mStartTime;
    @BindView(id = R.id.edit_meeting_end_time, click = true)
    private TextView mEndTime;
    @BindView(id = R.id.edit_meeting_pick_room, click = true)
    private TextView mPickRoom;
    @BindView(id = R.id.edit_meetings_submit, click = true)
    private Button mSubmit;

    private String mStartDate;
    private String startTime;
    private String endDate;
    private String endTime;
    private String roomid;

    private long mStartMillis;

    /**
     * 会议室是否已经选择
     */
    private boolean isRoomPicked = false;

    private MeetingsController mMeetingsController;
    private List<MeetingRoom> mRooms;

    @Override
    protected int getContentViewRes() {
        return R.layout.activity_edit_meeting;
    }

    @Override
    public void initWidget() {
        super.initWidget();
        CommonActionBar actionBar = getCommonActionBar();
        actionBar.setTitle("编辑会议");
        actionBar.setMoreVisible(false);

        bean = (MeetingByMonth) getIntent().getSerializableExtra("obj");

        Log.i("EditMeetingActivity", "bean = " + bean);

        String time = bean.getTime();
        String startDateTime = MeetingsController.getStartDateTime(time);
        mMeetingName.setText(bean.getTopic());
        mStartTime.setText(startDateTime);
        mEndTime.setText(MeetingsController.getEndDateTime(time));
        mPickRoom.setText(bean.getRoom());
        mStartDate = MeetingsController.getStartDate(time);
        startTime = MeetingsController.getStartTime(time);
        endDate = MeetingsController.getEndDate(time);
        endTime = MeetingsController.getEndTime(time);
        roomid = bean.getRoomid();

        mStartMillis = MeetingsController.getDateTimeInMillis(MeetingsController.getStartDateTime(time));

        mMeetingsController = new MeetingsController();
        mMeetingsController.fetchMeetingRooms(mRoomsCallBack);
    }

    private ListHttpCallBack<MeetingRoom> mRoomsCallBack = new ListHttpCallBack<MeetingRoom>() {

        @Override
        public void onSuccess(List<MeetingRoom> list) {
            mRooms = list;
        }

        @Override
        public void onError(int errCode, String str) {

        }
    };

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        int id = v.getId();
        switch (id) {
            case R.id.edit_meeting_start_time:
                setStartTime();
                break;

            case R.id.edit_meeting_end_time:
                setEndTime();
                break;

            case R.id.edit_meeting_pick_room:
                pickRoom();
                break;
            case R.id.edit_meetings_submit:
//                submit();
                setResult(MeetingDetailsActivity.EDIT_RESULT_CODE);
                finish();
                break;
        }
    }

    /**
     * 设置开始时间
     */
    private void setStartTime() {
        DateTimePickerDialog dialog = new DateTimePickerDialog(this, System.currentTimeMillis());
        dialog.setOnDateTimeSetListener(new DateTimePickerDialog.OnDateTimeSetListener() {
            @Override
            public void OnDateTimeSet(AlertDialog dialog, long date) {
                String dateTime = TimeUtil.getTargetDateTime(date);
                mStartTime.setText(dateTime);

                mStartDate = TimeUtil.getTargetDate(date, TimeUtil.DATE_FORMAT);
                startTime = TimeUtil.getTargetDate(date, TimeUtil.TIME_FORMAT);

                mStartMillis = date;

            }
        });
        dialog.show();
    }

    /**
     * 设置结束时间
     */
    private void setEndTime() {
        Date date = new Date(mStartMillis);
        date.setMinutes(date.getMinutes() + 30);
        DateTimePickerDialog dialog2 = new DateTimePickerDialog(this, date.getTime());
        dialog2.setOnDateTimeSetListener(new DateTimePickerDialog.OnDateTimeSetListener() {
            @Override
            public void OnDateTimeSet(AlertDialog dialog, long date) {
                String dateTime = TimeUtil.getTargetDateTime(date);
                mEndTime.setText(dateTime);

                endDate = TimeUtil.getTargetDate(date, TimeUtil.DATE_FORMAT);
                endTime = TimeUtil.getTargetDate(date, TimeUtil.TIME_FORMAT);

            }
        });
        dialog2.show();
    }

    private String[] mRoomNames;
    private String[] mRoomIds;

    private void pickRoom() {
        Builder builder = new Builder(this);
        builder.setTitle("请选择会议室");
        if (mRooms != null) {

            int size = mRooms.size();
            mRoomNames = new String[size];
            mRoomIds = new String[size];

            for (int i = 0; i < size; i++) {
                MeetingRoom room = mRooms.get(i);
                mRoomNames[i] = room.getRoom();
                mRoomIds[i] = room.getRoomid();
            }

            builder.setItems(mRoomNames, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mPickRoom.setText(mRoomNames[which]);
                    roomid = mRoomIds[which];
                    log(roomid);
                    isRoomPicked = true;
                }
            });
            android.support.v7.app.AlertDialog dialog1 = builder.create();
            dialog1.show();
        } else {
            toast("正在初始化数据，请稍后重试");
        }
    }

    private ProgressDialog mProgress;

    /**
     * 提交修改的会议到服务器
     */
    private void submit() {
        if (SmartCityApp.currentUser == null) {
            toast("请先登录");
            return;
        }

        log("EditMeeting", bean);

        bean.setTime(getTime());
        bean.setTopic(mMeetingName.getText().toString());
        bean.setRoom(mPickRoom.getText().toString());
        bean.setRoomid(roomid);

        mProgress = ProgressDialog.show(this, "", "正在修改...");
        mMeetingsController.updateMeetings(bean, new HttpCallBack() {
            @Override
            public void onSuccess(byte[] t) {
                try {
                    String data = new String(t, "GBK");
                    dealResult(data);
                    mProgress.dismiss();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                toast("修改会议失败！请检查网络连接");
                mProgress.dismiss();
            }
        });

    }

    private String getTime() {
        return mStartDate + "_" + endDate + " " + startTime + "-" + endTime;
    }

    /**
     * 处理修改会议后返回的结果
     * @param data
     */
    private void dealResult(String data) {

        if (!states.isEmpty()) {
            for (Map.Entry<String, String> entry : states.entrySet()) {
                String key = entry.getKey();
                if (key.equals(data)) {
                    toast(entry.getValue());
                    if (key.equals("OK")) {
                        setResult(MeetingDetailsActivity.EDIT_RESULT_CODE);
                        finish();
                    }
                    break;
                }
            }
        }

    }
}
